$(function () {
    if (location.href.indexOf("#reloaded") == -1) {
        location.href = location.href + "#reloaded";
        location.reload();
    }
    var newlist;
    let currentLi;
    let oldtime = getTime();
    window.oncontextmenu = function (e) {
        //取消默认的浏览器自带右键
        e.preventDefault();
    }
    getxx();
    function getxx() {
        // 2.从本地存储中获得元素给 “正在进行中”
        if (localStorage.getItem('todo')) {
            newlist = JSON.parse(localStorage.getItem('todo'));// 得到本地存储的列表
            // console.log(newlist);
            // 3. 如果done为false就给放进正在进行中
            $("#todolist").empty();
            $("#donelist").empty();
            $.each(newlist, function (i, ele) {
                var li = $("<li draggable='true' class='todoLi'></li>");
                if (ele.done == "false") {  //未完成就将数据放 “正在进行中”
                    $("#todolist").append(li);
                    li.attr("index", i);
                    li.html("<input type='checkbox'>" + ele.title + "<a href='javascript:;'></a>");
                } else if (ele.done == "true") {  //完成放到下面去
                    $("#donelist").append(li);
                    li.attr("index", i);
                    li.html("<input type='checkbox' checked>" + ele.title + "<a href='javascript:;'></a>");
                }
            });
            // 最后。改变数量
            $("#todocount").text($("#todolist li").length);
            $("#donecount").text($("#donelist li").length);
        } else {
            newlist = [];
        }

        getclick();
        getdelete();
        mouseRight();
        getTime();
        initTime();
        setInterval(() => { judgeTime() }, 1000); //实时更新时间
        drag();
        // getGif();
    }
    // 1. 按下回车 把完整数据 存储到本地存储里面  13
    $("#title").on("keyup", function (e) {
        if (e.keyCode == 13) {
            var content = $(this).val(); //表单值
            if (content.replace(/(^\s*)|(\s*$)/g, '').length <= 0) { //判断为空
                $(this).attr("placeholder", "输入值不应为空，请重试");
                return;
            }
            // 表单数据放进 数组里面
            var obj = new Object();
            obj.title = content;
            obj.done = "false";
            obj.index = null;
            newlist.unshift(obj); //每次的对象都放进数组里
            // 数组放进本地存储
            localStorage.setItem('todo', JSON.stringify(newlist));
            $(this).val(""); //清空里面的内容，方便下次打字
            $(this).attr("placeholder", "回车键入事项...");
            getxx();
        }
        getclick();
    });
    $(".addSvg").on("click", function () {
        $("#title").focus();

    })
    //pc拖动功能
    let parentId;
    function drag() {
        $.each($(".todoLi"), function (i, ele) {
            ele.querySelector("a").addEventListener("dragstart", (event) => { //a冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                event.preventDefault(); // 阻止默认行为
            });
            ele.querySelector("a").addEventListener("touchstart", (event) => { //a冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                // event.preventDefault(); // 阻止默认行为
            });
            ele.querySelector("a").addEventListener("dragenter", (event) => { //a冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                event.preventDefault(); // 阻止默认行为
            });
            ele.querySelector("a").addEventListener("touchmove", (event) => { //a冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                event.preventDefault(); // 阻止默认行为
            });
            ele.querySelector("input").addEventListener("dragstart", (event) => { //input冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                event.preventDefault(); // 阻止默认行为
            });
            ele.querySelector("input").addEventListener("dragenter", (event) => { //input冒泡阻止
                event.stopPropagation(); // 阻止冒泡
                event.preventDefault(); // 阻止默认行为
            });

            ele.addEventListener("dragstart", (event) => { //移动开始
                start(event);
            });
            ele.addEventListener("touchstart", (event) => { //移动端移动开始
                start(event);
            });
            ele.addEventListener("dragenter", (event) => { //移动中间
                enter(event);
            });
            ele.addEventListener("touchmove", (event) => { //移动端移动中间
                enterMobile(event);
            });
            ele.addEventListener("dragend", (event) => {
                currentLi.classList.remove('moving');

            });
            ele.addEventListener("click", (event) => {
                event.target.classList.remove('moving');
            })
            ele.addEventListener("touchend", (event) => {
                event.target.classList.remove('moving');
            })

        });
    }
    //a.移动开始
    function start(event) {
        // event.dataTransfer.effectAllowed = "move";
        currentLi = event.target;
        parentId = currentLi.parentNode.id;
        setTimeout(() => {
            currentLi.classList.add('moving')
        });
    }
    //b.移动过程-pc
    function enter(event) {
        event.preventDefault();// 阻止默认事件
        if (event.target === currentLi) {
            return
        }
        let flag;
        if (document.querySelector('#todolist').contains(event.target) && parentId == "todolist") { //当前元素在指定todolist父元素内
            // console.log("todolist");
            flag = true;
        } else if (document.querySelector('#donelist').contains(event.target) && parentId == "donelist") { //当前元素在指定donelist父元素内
            // console.log("donelist");
            flag = false;
        } else { //谁都不在
            console.log("不在范围内");
            // console.log(parentId);
            return;
        }
        let oldIndex = currentLi.getAttribute("index");
        let newIndex = event.target.getAttribute("index");
        if (oldIndex < newIndex) {
            currentLi.before(event.target)
            change();
        } else {
            currentLi.after(event.target);
            change();
        }
        function change() { //交换索引和数组位置
            let temp;
            let temp2;
            temp = currentLi.getAttribute("index");
            temp2 = newlist[currentLi.getAttribute("index")];
            newlist[currentLi.getAttribute("index")] = newlist[event.target.getAttribute("index")];
            newlist[event.target.getAttribute("index")] = temp2;
            currentLi.setAttribute("index", event.target.getAttribute("index"));
            event.target.setAttribute("index", temp);
            localStorage.setItem('todo', JSON.stringify(newlist));
        }
    }
    //c.移动过程--移动端
    function enterMobile(event) {
        event.preventDefault(); //阻止默认的滚动行为，以确保拖拽操作的顺畅性。
        let x = event.touches[0].clientX;
        let y = event.touches[0].clientY;
        let targetElment = document.elementFromPoint(x, y);
        if (event.target === targetElment || !targetElment.classList.contains("todoLi")) {
            return;
        };
        let flag;
        if (document.querySelector('#todolist').contains(targetElment) && parentId == "todolist") { //当前元素在指定todolist父元素内
            flag = true;
        } else if (document.querySelector('#donelist').contains(targetElment) && parentId == "donelist") { //当前元素在指定donelist父元素内
            flag = false;
        } else { //谁都不在
            console.log("不在范围内");
            return;
        };

        let oldIndex = event.target.getAttribute("index");
        let newIndex = targetElment.getAttribute("index");
        if (oldIndex < newIndex) {
            event.target.before(targetElment)
            change();
        } else {
            event.target.after(targetElment);
            change();
        }
        function change() { //交换索引和数组位置
            let temp;
            let temp2;
            temp = event.target.getAttribute("index");
            temp2 = newlist[event.target.getAttribute("index")];
            newlist[event.target.getAttribute("index")] = newlist[targetElment.getAttribute("index")];
            newlist[targetElment.getAttribute("index")] = temp2;
            event.target.setAttribute("index", targetElment.getAttribute("index"));
            targetElment.setAttribute("index", temp);
            localStorage.setItem('todo', JSON.stringify(newlist));
        }

    };
    // 4.点击checked表单，done变成true
    function getclick() {
        $("#todolist li input").on("change", function () {
            if ($(this).prop("checked") == true) {  //选中复选框
                // console.log(newlist);
                var index = $(this).parent().attr("index"); //拿到li的索引值、newlist索引值
                newlist[index].done = "true";// done= true
                localStorage.setItem('todo', JSON.stringify(newlist));
            }
            getxx();
        });
        ///
        $("#donelist li input").on("change", function () {
            if ($(this).prop("checked") == false) {  //没选中复选框
                var index = $(this).parent().attr("index"); //拿到li的索引值、newlist索引值
                newlist[index].done = "false";// done= false
                localStorage.setItem('todo', JSON.stringify(newlist));
            }
            getxx();
        });
        console.log("getclick调用");
    }
    // getclick();

    /// 删除功能
    function getdelete() {
        $("#todolist li a ,#donelist li a").on("click", function () {
            console.log($(this).parent().attr("index"));
            newlist.splice($(this).parent().attr("index"), 1);
            localStorage.setItem('todo', JSON.stringify(newlist));
            getxx();
        })
    };
    //日期功能
    function getTime() {
        let time = "";
        let date = new Date();
        let day = date.getDay();
        const arr = ["周日", "周一", "周二", "周三", "周四", "周五", "周六",];
        let minite = date.getMinutes();
        if (minite < 10) {
            minite = "0" + minite;
        }
        time = arr[day] + " " + date.getHours() + ":" + minite;
        return time;
    };
    //初始化日期
    function initTime() {
        let time = getTime()
        $(".timeLabel").html(time);
    }
    //判断日期是否更新
    function judgeTime() {
        let time = getTime();
        if (oldtime !== time) {
            $(".timeLabel").html(time);
            oldtime = time;
        }
    }

    //右键粘贴文本
    function mouseRight() {
        //class='todoLi' onmouseup='mouseRight(event)'
        $(".todoLi").on("mouseup", function (e) {
            if (e.button == 2) { //右键点击了
                //文本内容复制到剪贴板
                console.log(e.target.innerText);//文本内容
                let str = e.target.innerText;
                navigator.clipboard.writeText(str).then(
                    () => {
                        popDiv("粘贴文本成功");
                    },
                    () => {
                        popDiv("粘贴文本失败");
                    }
                );
            }
        })


        function popDiv(params) {
            //没有用节流
            let pop = $(".pop")
            //显示弹出框，并且节流
            pop.text(params);
            pop.removeClass("hide");
            pop.addClass("show");
            setTimeout(() => {
                pop.removeClass("show");
                pop.addClass("hide");
            }, 600);
        };
    }

    // 导航栏动画
    function getGif() {
        const gif = $(".header-gif");
        let distanceX = 0;
        let timer = setInterval(() => {
            distanceX += 51;
            gif.css("background-position-x", `-${distanceX}px`);
            if (distanceX >= 1000) {

                clearInterval(timer);
                distanceX = 0;
            }
        }, 400);

        // console.log(gif.css("background-position-x"));

    }













})